package com.payment.impl;

import java.util.List;
import java.util.Map;

import com.basic.service.contract.IBaseService;
import com.common.util.ListConvertMap;
import com.payment.IPaymentBehavior;
import com.translate.entity.NoticeCenter;
import com.translate.entity.Order;
import com.translate.entity.PayManager;
import com.translate.entity.ServiceManager;
import com.translate.entity.User;
import com.translate.vo.ServiceTypeVO;
import com.translate.web.constant.NotificationType;
import com.translate.web.constant.RedisConstant;
import com.translate.web.param.contract.IPayBehaviorRequestParam;
import com.translate.web.service.INoticeCenterService;
import com.translate.web.service.IOrderLogService;
import com.translate.web.service.IOrderService;
import com.translate.web.service.IPayManagerService;
import com.translate.web.service.IServiceTypeService;
import com.translate.web.service.IUserService;

/**
 * 普通支付
 * 
 * @author opjklu@126.com
 * @param <T>
 */
public class NormalPay<T> extends AbstractPay<T> implements IPaymentBehavior {

	public NormalPay(IBaseService<T>[] baseServices) {
		this.baseServices = baseServices;
	}

	private interface IParseOrder {

		/**
		 * {@inheritDoc}
		 * 
		 * @param behaviorRequestParam
		 * @param user
		 * @return
		 */
		int apply(IPayBehaviorRequestParam behaviorRequestParam, User user);
	}

	IParseOrder[] orders = new IParseOrder[] { (IPayBehaviorRequestParam behaviorRequestParam,
			User user) -> normalUserChangeStatus(behaviorRequestParam, user),
			(IPayBehaviorRequestParam behaviorRequestParam,
					User user) -> teamUserChangeStatus(behaviorRequestParam, user),

	};

	private int normalUserChangeStatus(IPayBehaviorRequestParam behaviorRequestParam, User user) {

		// 支付管理 订单状态变为 待确认
		IPayManagerService payManagerService = (IPayManagerService) baseServices[0];

		payManagerService.toBeConfirmed(behaviorRequestParam);

		// 更新订单状态
		IOrderService orderService = (IOrderService) baseServices[2];
		orderService.toBeConfirmed(behaviorRequestParam);

		return 1;
	}
	
	private int teamUserChangeStatus(IPayBehaviorRequestParam behaviorRequestParam, User user) {

		behaviorRequestParam.setUserId(user.getTeamId());
		
		// 支付管理 订单状态变为 待确认
		IPayManagerService payManagerService = (IPayManagerService) baseServices[0];

		payManagerService.toBeConfirmedByTeam(behaviorRequestParam);

		// 更新订单状态
		IOrderService orderService = (IOrderService) baseServices[2];
		orderService.toBeConfirmedByTeam(behaviorRequestParam);

		return 1;
	}
	
	

	@Override
	public int pay(IPayBehaviorRequestParam behaviorRequestParam) {

		
		
		IUserService userService = (IUserService)baseServices[1];
		
		int buyUserId = (int)behaviorRequestParam.getUserId();
		User userData = userService.selectByPrimaryKey( buyUserId);
		
		// 是不是团长
		Byte isRegimental = userData.getIsRegimental();
		
		Integer teamId = userData.getTeamId();
		if (0 == isRegimental && null != teamId && 0> teamId && 1 == userData.getStatus()) {
			throw new IllegalArgumentException("团员不能支付团长的订单");
		}
		
		// 添加订单记录
		List<Order> ordersByUserIdAndManagerId = orderCallbacks[isRegimental].apply(behaviorRequestParam, userData);

		int size = ordersByUserIdAndManagerId.size();
		if (0 == size) {
			return 0;
		}

		// 更新订单状态
		orders[isRegimental].apply(behaviorRequestParam, userData);
		
		

		// 添加日志
		IOrderLogService logService = (IOrderLogService) baseServices[3];
		
		int code = NotificationType.ORDER_NOTIFICATION.getValue();
		
		IServiceTypeService serviceTypeService = (IServiceTypeService) baseServices[6];
		
		List<ServiceTypeVO> listToCache = serviceTypeService.getListFromCache(ServiceTypeVO.class);

		Map<Integer, ServiceTypeVO> listToMap = ListConvertMap.listToMap(listToCache, ServiceTypeVO::getId);
		
		NoticeCenter[] notices = new NoticeCenter[size];
		
		NoticeCenter[] noticeAdmins = new NoticeCenter[size];
		
		if (1 == isRegimental) {
			
			IPayManagerService payManagerService = (IPayManagerService) baseServices[0];
			
			PayManager payManager = payManagerService.getPayManager(behaviorRequestParam.getId(), userData.getTeamId());
			
			User userInfoToCache = userService.getUserInfoToCache(payManager.getUserId());
			
			buyUserId = userInfoToCache.getId().intValue();
		}
		
		parseNotice(buyUserId, ordersByUserIdAndManagerId, notices, code, listToMap);
		
		parseNoticeAdmin(buyUserId, ordersByUserIdAndManagerId, userData, noticeAdmins, code, listToMap);
		
		INoticeCenterService noticeCenterService = (INoticeCenterService) baseServices[5];
		
		noticeCenterService.batchInsert(notices);
		
		noticeCenterService.batchInsert(noticeAdmins);
		
		try {
			IPayBehaviorRequestParam clone = behaviorRequestParam.clone();
			
			clone.setUserId(buyUserId);
			
			Integer serviceId;
			
			byte orderStatus = 22;
			
			for (Order item : ordersByUserIdAndManagerId) {
				
				serviceId = item.getServiceId();
				
				if (9 == serviceId || 10 == serviceId) {
					orderStatus = 3;
				}
			}
			
			return logService.toBeConfirmed(clone,
					ordersByUserIdAndManagerId.stream().mapToInt(e -> e.getId()).toArray(), orderStatus);
			
		} catch (CloneNotSupportedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new IllegalStateException(e.getMessage());
		}

	}
	
	private void parseNotice(int userId, List<Order> orders, NoticeCenter[] notices, int code,
			Map<Integer, ServiceTypeVO> listToMap) {
		NoticeCenter center;
		for (int i = 0; i < orders.size(); i++) {
			
			center = new NoticeCenter();
			
			Order order = orders.get(i);
			Integer serviceId = order.getServiceId();
			ServiceTypeVO item = listToMap.get(serviceId);
			
			if (null == item) {
				throw new IllegalStateException("找不到该服务编号：" + serviceId);
			}
			
			
			generateCenterList(center, code, userId, 
					order.getId(),
					"您的【" + item.getTypeName()+"】订单" + order.getOrderSnId() + "已创建，快去付款吧~");
			
			
			
			notices[i] = center;
		}
	}
	
	private void parseNoticeAdmin(int userId, List<Order> orders, User userData, NoticeCenter[] notices, int code,
			Map<Integer, ServiceTypeVO> listToMap) {
		
		String contentPrefix = 
				userData.getRealname().concat("(ID:") 
				+ userData.getId()+")提交【{TYPE_NAME}】订单{ORDER_SN},请及时查看处理!";
		
		
		NoticeCenter center;
		String msg;
		for (int i = 0; i < orders.size(); i++) {
			
			center = new NoticeCenter();
			
			Order order = orders.get(i);
			Integer serviceId = order.getServiceId();
			ServiceTypeVO item = listToMap.get(serviceId);
			
			if (null == item) {
				throw new IllegalStateException("找不到该服务编号：" + serviceId);
			}
			
			msg = contentPrefix
					.replace("{TYPE_NAME}", item.getTypeName())
					.replace("{ORDER_SN}", order.getOrderSnId());

			generateCenterList(center, code, userId, 
					order.getId(),
					msg);
			
			center.setTitle("提交订单");
			
			center.setPlatform((byte) 1);
			
			notices[i] = center;
		}
	}

	private void generateCenterList(NoticeCenter noticeCenter,
			int noticeType, 
			int userId, 
			int typeId, 
			String content
	) {
		
		noticeCenter.setNoticeType((byte) noticeType);
		
		noticeCenter.setUserId(userId);
		
		noticeCenter.setTypeId(typeId);
		
		noticeCenter.setTitle("创建订单");
		
		noticeCenter.setTranslateType((byte) 0);
		
		noticeCenter.setNoticeContent(content);
		
		long timeMillis = System.currentTimeMillis() / 1000;
		
		noticeCenter.setCreateTime(timeMillis);
		
		noticeCenter.setUpdateTime(timeMillis);
		
		
	}
	
	

}
